<template>
  <div id="qcRuleDiv">
    <Breadcrumb content="质控规则设置" />
    <div class="bodyContent">
      <Splitpanes>
        <!-- 左侧表格  -->
        <Pane size="60">
          <vxe-toolbar perfect>
            <template #buttons>
              <div class="smallToolTitle">质控规则</div>
              <vxe-input
                style="width: 130px"
                v-model="searchForm.searchValue"
                type="search"
                clearable
                class="vxeInputSearch"
                placeholder="关键字查询"
                @clear="findQcRuleList"
                @keyup="keyupEnter"
                @search-click="handleSearch(searchForm.searchValue)"
              ></vxe-input>
              <vxe-button
                type="text"
                class="button-blue"
                icon="vxe-icon-refresh"
                content="刷新"
                :loading="tloading"
                @click="findQcRuleList"
              ></vxe-button>
              <vxe-button
                type="text"
                class="button-blue"
                icon="vxe-icon-square-plus"
                content="新建"
                @click="addRuleDialog()"
              ></vxe-button>
            </template>
          </vxe-toolbar>

          <div class="tableBody">
            <vxe-table
              ref="ruleTableRef"
              class="mytable-scrollbar"
              border="inner"
              align="center"
              height="auto"
              :data="ruleList"
              :loading="tloading"
              @current-change="ruleRowClick"
              :row-config="{ isCurrent: true, isHover: true }"
              :column-config="{ resizable: true }"
              resizable
              show-overflow
              keep-source
            >
              <vxe-column title="序号" width="80">
                <template #default="{ row, rowIndex, column }">
                  <span>{{ rowIndex + (page.currentPage - 1) * page.pageSize + 1 }}</span>
                </template>
              </vxe-column>

              <vxe-column field="name" title="名称" width="100"> </vxe-column>
              <vxe-column field="code" title="编码" width="100"> </vxe-column>
              <vxe-column field="isStatic" title="是否静态" width="180">
                <template #default="{ row, rowIndex, column }">
                  <el-tag :type="getIsStaticTagType(row)">{{ getIsStaticStatusDesc(row) }}</el-tag>
                </template>
              </vxe-column>
              <vxe-column field="remark" title="说明" width="500"> </vxe-column>
              <vxe-column field="seq" title="顺序" width="50"> </vxe-column>
              <vxe-column title="操作" fixed="right">
                <template #default="{ row }">
                  <vxe-button
                    type="text"
                    status="danger"
                    icon="vxe-icon-delete"
                    circle
                    @click.native="deleteRule(row)"
                    class="spanIcon"
                  ></vxe-button>
                </template>
              </vxe-column>
            </vxe-table>
            <vxe-pager
              align="left"
              min-height="32px"
              :current-page.sync="page.currentPage"
              :page-size.sync="page.pageSize"
              :total="page.totalResult"
              :layouts="[
                'PrevJump',
                'PrevPage',
                'Number',
                'NextPage',
                'NextJump',
                'Sizes',
                'FullJump',
                'Total'
              ]"
              @page-change="handleSizeChange($event)"
            ></vxe-pager>
          </div>
        </Pane>

        <!-- 右侧表单 -->
        <Pane size="40">
          <div class="toolbartitle">基本信息</div>
          <el-form
            ref="ruleFormRef"
            :model="ruleForm"
            :rules="ruleFormRule"
            label-width="100px"
            class="form-input-m"
            inline-message
          >
            <el-row>
              <el-col :span="24">
                <el-form-item prop="name" label="名称">
                  <el-input
                    type="text"
                    v-model="ruleForm.name"
                    placeholder="请输入名称"
                    clearable
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item prop="code" label="编码">
                  <el-input
                    type="text"
                    v-model="ruleForm.code"
                    placeholder="请输入编码"
                    clearable
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item prop="ruleType" label="规则类型">
                  <el-select v-model="ruleForm.ruleType" filterable placeholder="请选择规则类型">
                    <el-option
                      v-for="ruleType in ruleTypeList"
                      :key="ruleType.id"
                      :label="ruleType.name"
                      :value="ruleType.code"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item prop="acnt" label="A" class="input-s">
                  <el-input-number v-model="ruleForm.acnt" :min="0" :max="1000"></el-input-number>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item prop="ncnt" label="N" class="input-s">
                  <el-input-number v-model="ruleForm.ncnt" :min="0" :max="1000"></el-input-number>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item prop="lcnt" label="L" class="input-s">
                  <el-input-number
                    v-model="ruleForm.lcnt"
                    :min="0.0"
                    :precision="2"
                    :max="1000"
                  ></el-input-number>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="是否静态" prop="isStatic">
                  <el-switch
                    v-model="ruleForm.isStatic"
                    inline-prompt
                    active-text="是"
                    inactive-text="否"
                  ></el-switch>
                </el-form-item>
              </el-col>
              <el-col :span="21">
                <el-form-item prop="remark" label="说明">
                  <el-input
                    type="textarea"
                    v-model="ruleForm.remark"
                    placeholder="请输入说明"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="状态">
                  <el-radio-group v-model="ruleForm.status">
                    <el-radio :label="0">启用</el-radio>
                    <el-radio :label="1">禁用</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item prop="seq" label="顺序">
                  <el-input-number v-model="ruleForm.seq" :min="1" :max="1000" />
                </el-form-item>
              </el-col>

              <el-col :span="24">
                <el-form-item class="form-footer">
                  <template #default>
                    <el-button type="primary" @click="saveRule('ruleFormRef')">保存</el-button>
                    <el-button type="default" @click="resetForm(ruleForm)">重置</el-button>
                  </template>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </Pane>
      </Splitpanes>
    </div>
  </div>
</template>
<script setup lang="ts">
// 引入组件区 ==========
import { ref, reactive, getCurrentInstance, onMounted } from 'vue';
import Breadcrumb from '@/components/Breadcrumb.vue';
import { Splitpanes, Pane } from 'splitpanes';
let { proxy }: any = getCurrentInstance();
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage'; //提示框

// 全局变量定义区 ==========
// 根据质控规则的关键字查询
let searchForm = {
  searchValue: ''
};
let tloading = ref(false); //加载状态
let ruleList: any = reactive([]); //质控规则列表表格
let ruleTypeList: any = reactive([]); //右侧表单字典表：指控规则类型

// 条数/页
const PageSizeList = [10, 50, 100, 200, 500];
// 分页
let page = reactive({
  currentPage: 1,
  pageSize: PageSizeList[1],
  totalResult: 0
});

// 右侧基本信息表单
let ruleForm = reactive({
  id: null,
  name: '',
  code: '',
  ruleType: '',
  acnt: 0,
  ncnt: 0,
  lcnt: 0.0,
  status: 0,
  seq: 1,
  remark: '',
  isStatic: true
});

// 右侧基本信息表单检验
let ruleFormRule = {
  name: [
    {
      required: true,
      message: '请输入规则名称',
      trigger: 'blur'
    },
    {
      min: 2,
      max: 20,
      message: '长度为2到20个字符',
      trigger: 'blur'
    }
  ]
};

// 方法定义区 =============
// 页面加载时更新列表(左侧)
onMounted(() => {
  findQcRuleList(); // 获取质控规则表格数据
  getDictDetailList();
});

// 获取质控规则表格数据
function findQcRuleList() {
  tloading.value = true;
  ruleList.length = 0; //放入数据前清空数据
  const url = '/api/qc/qcRule/findRulePageList';
  proxy.$http
    //注意此处的数据条数
    .get(url, {
      params: { pageIndex: page.currentPage, pageSize: page.pageSize }
    })
    .then((res: any) => {
      ruleList.push(...res.data.records);
      page.totalResult = res.data.total;
      tloading.value = false;
      ruleRowClick({ row: ruleList[0] }); //默认选中第一条数据
    })
    .catch((err: any) => {
      tloading.value = false;
      // VxeMessage('获取获取当前字典的规则列表失败',VxeNotifyType.error)
    });
}

// 获取是否静态的tag标记(绿/红)
function getIsStaticTagType(row: any) {
  if (row.isStatic) {
    return 'success';
  } else {
    return 'danger';
  }
}
// 获取是否静态文字(是/否)
function getIsStaticStatusDesc(row: any) {
  if (row.isStatic) {
    return '是';
  } else {
    return '否';
  }
}

// 回车查询
function keyupEnter(e: any) {
  if (e.$event.code == 'Enter') {
    handleSearch(searchForm.searchValue);
  }
}
// 查询/刷新(关键字)
function handleSearch(row: string | number) {
  tloading.value = true;
  const url = '/api/qc/qcRule/findRulePageList';
  ruleList.length = 0;
  proxy.$http
    .get(url, {
      params: { seachValue: row, pageIndex: 1, pageSize: 50 }
    })
    .then((res: any) => {
      ruleList.push(...res.data.records);
      page.totalResult = res.data.total;
      tloading.value = false;
      ruleRowClick({ row: ruleList[0] }); //默认选中第一条数据
    })
    .catch((err: any) => {
      tloading.value = false;
      VxeMessage('查询刷新失败', VxeNotifyType.error);
    });
}

//点击每页数量(分页查询)
function handleSizeChange({ type, currentPage, pageSize }) {
  if (type === 'size') {
    page.currentPage = 1;
  } else {
    page.currentPage = currentPage;
  }
  page.pageSize = pageSize;
  findQcRuleList();
}

// 删除当前行规则
function deleteRule(row: any) {
  proxy
    .$confirm('确定删除此规则？', '提示', {
      cancelButtonClass: 'cancel-button',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    .then(async () => {
      const url = '/api/qc/qcRule/deleteRule';
      proxy.$http.post(url, row).then((res: any) => {
        if (res.status.code === 1) {
          findQcRuleList();
          VxeMessage('删除规则成功', VxeNotifyType.success);
        } else {
          VxeMessage(res.status.msg, VxeNotifyType.error);
        }
      });
    })
    .catch((err: any) => {
      // VxeMessage(err, VxeNotifyType.error);
    });
}

// 编辑当前行规则
function setRuleForm(row: any) {
  ruleForm.id = row.id;
  ruleForm.code = row.code;
  ruleForm.name = row.name;
  ruleForm.ruleType = row.ruleType;
  ruleForm.acnt = parseInt(row.acnt, 10);
  ruleForm.ncnt = parseInt(row.ncnt, 10);
  ruleForm.lcnt = parseInt(row.lcnt, 10);
  ruleForm.status = row.status;
  ruleForm.isStatic = row.isStatic;
  ruleForm.seq = row.seq;
  ruleForm.remark = row.remark;
}

// 清空中间规则弹框表单
function clearForm() {
  ruleForm.id = null;
  ruleForm.code = '';
  ruleForm.name = '';
  ruleForm.ruleType = '';
  ruleForm.acnt = 0;
  ruleForm.ncnt = 0;
  ruleForm.lcnt = 0.0;
  ruleForm.status = 0;
  ruleForm.seq = page.totalResult + 1;
  ruleForm.remark = '';
  ruleForm.isStatic = true;
}

// 点击设计模式表格当前行触发右侧表单变化
function ruleRowClick({ row }: any) {
  if (IsEmpty(row)) {
    clearForm();
  } else {
    (proxy.$refs.ruleTableRef as any).setCurrentRow(row);
    setRuleForm(row);
  }
}
// 新建
function addRuleDialog() {
  clearForm();
  (proxy.$refs.ruleTableRef as any).clearCurrentRow();
}

// 规则弹框保存
function saveRule(formName: any) {
  let $el = proxy.$refs[formName];
  $el.validate((valid: any) => {
    if (!valid) {
      return false;
    }
    if (ruleForm.id === null) {
      const url = '/api/qc/qcRule/addRule';
      const rule = {
        code: ruleForm.code,
        name: ruleForm.name,
        ruleType: ruleForm.ruleType,
        acnt: ruleForm.acnt,
        ncnt: ruleForm.ncnt,
        lcnt: ruleForm.lcnt,
        status: ruleForm.status,
        isStatic: ruleForm.isStatic,
        seq: ruleForm.seq,
        remark: ruleForm.remark
      };
      proxy.$http
        .post(url, rule)
        .then((res: any) => {
          VxeMessage('新增规则成功', VxeNotifyType.success);
          clearForm();
          findQcRuleList();
        })
        .catch((err: any) => {
          VxeMessage('新增规则失败', VxeNotifyType.error);
        });
    } else {
      // 修改用户
      const url = '/api/qc/qcRule/editRule';
      const rule = {
        id: ruleForm.id,
        code: ruleForm.code,
        name: ruleForm.name,
        ruleType: ruleForm.ruleType,
        acnt: ruleForm.acnt,
        ncnt: ruleForm.ncnt,
        lcnt: ruleForm.lcnt,
        status: ruleForm.status,
        isStatic: ruleForm.isStatic,
        seq: ruleForm.seq,
        remark: ruleForm.remark
      };
      proxy.$http
        .post(url, rule)
        .then((res: any) => {
          VxeMessage('修改规则成功', VxeNotifyType.success);
          setTimeout(() => {
            clearForm();
            findQcRuleList();
          }, 500);
        })
        .catch((err: any) => {
          VxeMessage('修改规则失败', VxeNotifyType.error);
        });
    }
  });
}

// 右侧重置按钮
function resetForm(row: any) {
  if (IsEmpty(row)) {
    clearForm();
    return;
  }
  ruleForm.code = '';
  ruleForm.name = '';
  ruleForm.ruleType = '';
  ruleForm.acnt = 0;
  ruleForm.ncnt = 0;
  ruleForm.lcnt = 0.0;
  ruleForm.status = 0;
  ruleForm.remark = '';
  ruleForm.isStatic = true;
}

//从词典获取所有的报告组
// 获取界面规则
function getDictDetailList() {
  ruleTypeList.length = 0;
  const url = '/api/sys/basDictDetail/findDictDetailList';
  proxy.$http
    .get(url, { params: { code: 'QCRULE' } })
    .then((res: any) => {
      //console.log('reportTypeList---------------',reportTypeList);
      ruleTypeList.push(...res.data);
    })
    .catch((err: any) => {
      proxy.$alert(err, '提示');
    });
}

//**判断为空*/
function IsEmpty(value: any) {
  if (value === undefined || value === '' || value === null) {
    return true;
  }
  if (JSON.stringify(value) === '{}') {
    return true;
  }
  return false;
}
</script>

<style lang="scss" scoped>
#qcRuleDiv {
  height: 100%;
  .bodyContent {
    height: calc(100% - 60px);
    .splitpanes {
      background-color: $base-white;
    }
    // 附加按钮间距
    .button-blue {
      margin: 5px 0 5px 5px;
    }
    .tableBody {
      height: calc(100% - 40px - 32px);
    }

    // 每个单元格左内边距
    :deep(.vxe-cell) {
      padding-left: 5px;
    }
    // 弹框
    .el-dialog {
      font-weight: 700;
      max-height: 1000px;
    }
  }
}
</style>
